import { _decorator, Component, Prefab, view, Node, instantiate, TiledMap} from "cc";
import {WebView, assetManager, resources, TextAsset } from "cc"
const { ccclass, property } = _decorator;

declare const qq:any;

@ccclass
export default class MapController  extends Component {

    @property(WebView)
    webView: WebView | null = null;

    @property(TextAsset)
    html_file : TextAsset | null = null;


    protected onLoad(): void {
        
        if(this.webView){
            this.webView.node.zIndex = 0;
        }

        // 加载 HTML 文件并设置 WebView 的 URL
        resources.load('map', (err, data) => {
            if (err) {
                console.error('Failed to load map:', err);
                return;
            }
            
            const htmlcontents = data.text;
            var blob = new Blob([htmlcontents], {type: 'text/html'});
            const url = URL.createObjectURL(blob);
            if (this.webView) {
                this.webView.url = url;
                this.webView.node.zIndex = 0;
                console.info("zIndex=%d",this.webView.node.zIndex);
            }
        });

        // 监听来自 WebView 的消息
        window.addEventListener('message', this.onMessageReceived.bind(this));
    }

    onMessageReceived(event){
        const data = event.data;
        if (data.action === 'mapClick') {
            const { lng, lat } = data.params;
            console.log(`Map clicked at longitude: ${lng}, latitude: ${lat}`);
            // 这里可以添加处理逻辑，例如在 Cocos 中显示点击位置等
        }        
    }

    sendMessageToWebView(action, params) {
        if (this.webView) {
            const contentWindow = (this.webView.node as any)._contentWindow; // 获取 WebView 的内容窗口
            if (contentWindow) {
                contentWindow.postMessage({
                    action: action,
                    params: params
                }, '*');
            }
        }
    }

    // 示例：设置地图中心点
    setMapCenter(lng: number, lat: number) {
        this.sendMessageToWebView('setCenter', { lng, lat });
    }

}
